package cn.wit.sst.view;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import cn.wit.sst.components.SpreadsheetHelper;
import cn.wit.sst.dto.StudentDto;
import cn.wit.sst.service.StudentService;
import cn.wit.sst.utils.AppCache;
import cn.wit.sst.utils.Dialogs;
import io.reactivex.Observable;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import io.reactivex.schedulers.Schedulers;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;

@Controller
public class StudentController {
	private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    @FXML TextField txtStuNo;
    @FXML Label txtName;
    @FXML Label txtSno;
    @FXML Label txtClazz;
    @FXML ProgressBar progressBar;
	@FXML Label txtMajor;
	@FXML Label txtYear;

	@FXML TitledPane infoPane;
	@FXML TitledPane scorePane;

    @Autowired
    StudentService studentService;

    @Autowired
    AppCache appCache;

	@FXML
	public void initialize() {
	}

	@FXML
    protected void handleSearchAction(ActionEvent event) {
    	String sno = txtStuNo.getText();
    	if (StringUtils.isEmpty(sno)) {
    		Dialogs.alert("请输入学号！");
    	} else {
    		doSearch();
    	}
    }

    private void doSearch() {
    	Long sno = Long.valueOf(txtStuNo.getText());

		Observable.just(txtStuNo.getText())
			.doOnNext(s -> onBeforeSearch())
			.debounce(300, TimeUnit.MILLISECONDS)		// 延迟300ms，避免查询过快时进度条一闪而过
			.observeOn(Schedulers.io())					// 指定接下来的操作在后台线程执行
			.map(q -> studentService.queryAllScores(sno))
			.observeOn(JavaFxScheduler.platform())		// 指定接下来的操作在UI线程执行
			.subscribe(scoreList -> showScores(scoreList),
				e -> onSearchError(e) // 查询结束，或者出错
			);
    }

    // 查询学生信息完成，这个方法需要在ui线程执行
    private void showScores(StudentDto s) {
    	progressBar.setVisible(false);

		if (s == null) {
			Dialogs.alert("没有该学号对应的学生！");
		} else {
			txtName.setText(s.getName());
			txtClazz.setText(s.getClazz() + "");
			txtMajor.setText(s.getMajor());
			txtSno.setText(s.getSno() + "");
			txtYear.setText(s.getYear() + "");

			scorePane.setContent(SpreadsheetHelper.createSheet(s.getScores()));
		}
	}

	private void onBeforeSearch() {
		progressBar.setVisible(true);	// 查询之前的操作：显示进度条
    }

    // 查询出错
    private void onSearchError(Throwable e) {
    	progressBar.setVisible(false);

    	logger.error("查询出错", e);

    	Dialogs.alert("查询出错：" + e.getMessage());
    }
}
